import org.json.JSONObject;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// GetBook类继承HttpServlet，用于查询指定书号的图书信息
@WebServlet("/get_book")
public class GetBook extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // 数据库连接相关配置信息
    private static final String URL = "jdbc:mysql://localhost:3306/linux_exam";
    private static final String USER = "root";
    private static final String PASSWORD = "1qaz@WSX#EDC";

    // 处理GET请求，根据传入的图书编号查询图书信息并返回相应结果给客户端
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置跨域请求相关头信息
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
        // 设置响应内容类型为JSON格式
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // 获取要查询图书的编号（从请求参数中获取）
        String bookNumber = request.getParameter("number");

        if (bookNumber == null || bookNumber.isEmpty()) {
            // 如果图书编号参数为空值，返回错误信息
             JSONObject errorJson = new JSONObject();
            errorJson.put("error", "图书编号不能为空");
            out.println(errorJson.toString());
            out.close();
            return;
        }

        JSONObject resultJson = getBook(bookNumber);
        if (resultJson!= null) {
            out.println(resultJson.toString());
        } else {
            JSONObject errorJson = new JSONObject();
            errorJson.put("error", "未查询到指定图书信息");
            out.println(errorJson.toString());
        }

        out.close();
    }

    // 根据图书编号从数据库中查询图书信息
     public JSONObject getBook(String bookNumber) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 加载驱动
   Class.forName("com.mysql.cj.jdbc.Driver");
            // 建立数据库连接
          connection = DriverManager.getConnection(URL, USER, PASSWORD);

            // 编写查询图书的SQL语句，使用预编译防止SQL注入（字段有number、name、author等）
           String sql = "SELECT * FROM t_book WHERE number =?";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, bookNumber);

            // 执行查询操作，获取结果集
             resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                JSONObject bookInfo = new JSONObject();
                bookInfo.put("number", resultSet.getString("number"));
                bookInfo.put("name", resultSet.getString("name"));
                bookInfo.put("author", resultSet.getString("author"));
                 return bookInfo;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭数据库相关资源
            try {
                if (resultSet!= null) resultSet.close();
                if (preparedStatement!= null) preparedStatement.close();
                if (connection!= null) connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
}
}





















